package upload

import (
	"context"
	"github.com/qiniu/api.v7/v7/auth/qbox"
	"github.com/qiniu/api.v7/v7/storage"
	"github.com/vueadmin/global"
	"mime/multipart"
	"strings"
)

var QiniuOss = new(qiniu)

type qiniu struct{}

//上传
func (p qiniu) Upload(file *multipart.FileHeader, key string) string {
	putPlicy := storage.PutPolicy{
		Scope: global.CONF.QiniuOss.Bucket,
	}
	mac := qbox.NewMac(global.CONF.QiniuOss.AccessKey, global.CONF.QiniuOss.SecretKey)

	upToken := putPlicy.UploadToken(mac)

	formUploader := storage.NewFormUploader(p.qiniuConfig())

	ret := storage.PutRet{}        // 上传后返回的结果
	putExtra := storage.PutExtra{} // 额外参数

	f, openError := file.Open()
	if openError != nil {
		panic(openError)
	}
	defer f.Close()

	if err := formUploader.Put(context.Background(), &ret, upToken, strings.TrimLeft(key, "/"), f, file.Size, &putExtra); err != nil {
		panic(err)
	}

	return global.CONF.QiniuOss.Domain + key
}

//删除图片
func (p qiniu) DeleteFile(key string) bool {
	mac := qbox.NewMac(global.CONF.QiniuOss.AccessKey, global.CONF.QiniuOss.SecretKey)
	cfg := p.qiniuConfig()
	bucketManager := storage.NewBucketManager(mac, cfg)
	if err := bucketManager.Delete(global.CONF.QiniuOss.Bucket, key); err != nil {
		panic(err)
	}
	return true
}

//获取机房位置
func (p qiniu) qiniuConfig() *storage.Config {
	cfg := storage.Config{
		UseHTTPS:      global.CONF.QiniuOss.UseHTTPS,
		UseCdnDomains: global.CONF.QiniuOss.UseCdnDomains,
	}
	switch global.CONF.QiniuOss.Zone { // 根据配置文件进行初始化空间对应的机房
	case "ZoneHuadong":
		cfg.Zone = &storage.ZoneHuadong
	case "ZoneHuabei":
		cfg.Zone = &storage.ZoneHuabei
	case "ZoneHuanan":
		cfg.Zone = &storage.ZoneHuanan
	case "ZoneBeimei":
		cfg.Zone = &storage.ZoneBeimei
	case "ZoneXinjiapo":
		cfg.Zone = &storage.ZoneXinjiapo
	}
	return &cfg
}
